<template>
  <div class="login-container">
    <div class="login-box">
      <h1>登录</h1>
      <el-form
        ref="form"
        :model="form"
        @submit.native.prevent="handleLogin"
        :rules="rules"
        class="login-form"
        label-width="100px"
      >
        <el-form-item prop="username" label="用户名">
          <el-col :span="21">
            <el-input
              v-model="form.username"
              placeholder="请输入用户名"
              prefix-icon="el-icon-user"
              auto-complete="false"
              class="input-field"
            />
          </el-col>
        </el-form-item>
        <el-form-item prop="password" label="密码">
          <el-col :span="21">
            <el-input
              v-model="form.password"
              type="password"
              placeholder="请输入密码"
              auto-complete="false"
              prefix-icon="el-icon-lock"
              class="input-field"
            />
          </el-col>
        </el-form-item>
        <el-form-item prop="code" label="验证码">
          <el-col :span="13">
            <el-input
              placeholder="请输入验证码"
              v-model="form.code"
              auto-complete="false"
              class="input-field"
            >
              <i slot="prefix" class="el-icon-tickets"></i>
            </el-input>
          </el-col>
          <canvas
            id="canvas"
            width="90px"
            height="40px"
            style="margin-left: 10px"
            @click="handleDraw"
          ></canvas>
        </el-form-item>
        <el-button
          type="primary"
          native-type="submit"
          :loading="loading"
          class="login-button"
        >
          登录
        </el-button>
      </el-form>
      <el-button
        type="text"
        @click="$router.push({ name: 'AdminLogin' })"
        class="admin-login-button"
      >
        管理员登录
      </el-button>
      <div v-if="errorMessage" class="error-message">{{ errorMessage }}</div>
    </div>
  </div>
</template>

<script>

import { mapActions } from "vuex";
export default {
  name: "UserLogin",
  data() {
    return {
      imgCode: "",
      allTexts: "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890",
      form: {
        username: "",
        password: "",
        code: "",
      },
      loading: false,
      errorMessage: "",
      rules: {
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" },
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
        ],
        code: [
          { required: true, message: "验证码不能为空", trigger: "blur" },
          { validator: this.checkCode, trigger: "blur" },
        ],
      },
    };
  },
  mounted() {
    this.handleDraw();
  },
  methods: {
    ...mapActions({
      userLogin: "user/USER_LOGIN",
    }),
    checkCode(rule, value, callback) {
      console.log(this.form.code);
      if (this.form.code.toLowerCase() !== this.imgCode.toLowerCase()) {
        return callback(new Error("验证码不正确"));
      } else {
        return callback();
      }
    },
    handleLogin() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.loading = true;
          // this.errorMessage = "";
          this.loading = true;
          this.userLogin(this.form)
            .then(() => {
              this.$router.push({ path: "/shop" });
            })
            .catch((err) => {
              console.log("异常", err.message);
            })
            .finally(() => {
              this.loading = false;
            });
        } else {
          this.$message({
            showClose: true,
            message: "表单填写有误，请检查后再试",
            type: "error",
          });
          // this.errorMessage = "表单填写有误，请检查后再试";
          this.handleDraw();
        }
      });
    },
    handleDraw() {
      this.imgCode = this.draw();
    },
    randomNum(min, max) {
      return parseInt(Math.random() * (max - min) + min);
    },
    randomColor(min, max) {
      const r = this.randomNum(min, max);
      const g = this.randomNum(min, max);
      const b = this.randomNum(min, max);
      return `rgb(${r},${g},${b})`;
    },
    draw() {
      const canvas = document.getElementById("canvas");
      const ctx = canvas.getContext("2d");
      ctx.fillStyle = this.randomColor(180, 230);

      ctx.fillRect(0, 0, 90, 40);
      let imgCode = "";
      const totalChars = 4; // 验证码字符总数
      const charWidth = 90 / totalChars; // 每个字符的宽度
      const charHeight = 40; // 每个字符的高度
      const charSpacing = 2; // 字符之间的间隔
      for (let i = 0; i < 4; i++) {
        const text = this.allTexts[this.randomNum(0, this.allTexts.length)];
        imgCode += text;
        const fontSize = Math.floor((charHeight - charSpacing) / 1.5);
        const deg = this.randomNum(-10, 10);
        ctx.font = fontSize + "px Arial";
        ctx.textBaseline = "top";
        ctx.fillStyle = this.randomColor(80, 150);
        ctx.save();
        ctx.translate((i + 0.5) * charWidth, charHeight / 2);
        ctx.rotate((deg * Math.PI) / 180);
        ctx.fillText(text, -15 + 5, -15);
        ctx.restore();
      }
      for (let i = 0; i < 5; i++) {
        ctx.beginPath();
        ctx.moveTo(this.randomNum(0, 90), this.randomNum(0, 40));
        ctx.lineTo(this.randomNum(0, 90), this.randomNum(0, 40));
        ctx.strokeStyle = this.randomColor(180, 230);
        ctx.closePath();
        ctx.stroke();
      }
      for (let i = 0; i < 40; i++) {
        ctx.beginPath();
        ctx.arc(
          this.randomNum(0, 90),
          this.randomNum(0, 40),
          1,
          0,
          2 * Math.PI
        );
        ctx.closePath();
        ctx.fillStyle = this.randomColor(150, 200);
        ctx.fill();
      }
      console.log(imgCode);
      return imgCode;
    },
  },
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: #fff;
}

.login-box {
  background: rgba(255, 255, 255, 0.9);
  padding: 30px;
  border-radius: 15px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
  width: 400px;
  text-align: center;
}

.login-box h1 {
  font-size: 28px;
  margin-bottom: 20px;
  color: #333;
}

.login-form {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.login-form .el-form-item {
  width: 100%;
  margin-bottom: 15px;
}

.input-field {
  width: 100%;
  border: 1px solid #ddd;
  border-radius: 5px;
  transition: border-color 0.3s ease;
}

.input-field:focus {
  border-color: #4facfe;
}

.login-button {
  width: 100%;
  margin-top: 10px;
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  border: none;
  border-radius: 5px;
  padding: 10px;
  color: #fff;
  font-size: 16px;
  cursor: pointer;
  transition: background 0.3s ease;
}

.login-button:hover {
  background: linear-gradient(135deg, #00f2fe 0%, #4facfe 100%);
}

.admin-login-button {
  margin-top: 10px;
  text-align: center;
  color: #4facfe;
  cursor: pointer;
}

.admin-login-button:hover {
  text-decoration: underline;
}

.error-message {
  color: red;
  margin-top: 10px;
  text-align: center;
}
canvas {
  float: left;
}
</style>